package com.example.gslih.myapplication.permission;

import android.content.Context;
import android.support.v4.app.FragmentActivity;

import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import io.reactivex.functions.Consumer;

/**
 * 需要引入
 implementation 'io.reactivex.rxjava2:rxjava:2.2.3'
 implementation 'com.github.tbruyelle:rxpermissions:0.10.2'
 */
public class TtPermissionUtil {

    private PermissionResultInterface mPermissionResultInterface;
    private Context mContext;

    public TtPermissionUtil(Context context, PermissionResultInterface mPermissionResultInterface) {
        mContext = context;
        this.mPermissionResultInterface = mPermissionResultInterface;
    }

    //全部同意为true  一个拒绝授权为false
    public void checkPermissionAll(String...permissions){
        RxPermissions rxPermissions = new RxPermissions((FragmentActivity) mContext);
        rxPermissions.request(permissions)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean){
                            mPermissionResultInterface.mounted(null);
                        }else {
                            mPermissionResultInterface.unmounted(null);
                        }
                    }
                });
    }

    //请求每一个权限都会调用
    public void checkPermissionEach(String...permissions){
        RxPermissions rxPermissions = new RxPermissions((FragmentActivity) mContext);
        rxPermissions.requestEach(permissions)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted){
                            mPermissionResultInterface.mounted(permission);
                        }else {
                            mPermissionResultInterface.unmounted(permission);
                        }
                    }
                });
    }

    public interface PermissionResultInterface{
        void mounted(Permission permission);
        void unmounted(Permission permission);
    }
}
